package com.noble.meether.logic.offline;

import android.os.Build;

import com.noble.glamour.module.local.chat.utils.MsgUtils;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.library.log.PLogger;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.meether.chat.msgtype.base.BaseMessage;
import com.noble.meether.chat.ui.imui.util.IMChatUtil;
import com.noble.meether.logic.offline.bean.OfflineBean;
import com.noble.meether.logic.offline.bean.OfflineMsg;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 离线消息管理类
 * Created by Su on 2017/9/23.
 */
public class OfflineMgr implements ModuleBase {

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    // ------------------------------------- 离线消息处理 ------------------------------------

    /**
     * 获取离线消息并处理
     */
    public void getOfflineMsg() {
        reqOfflineMsg(response -> {
            PLogger.d("offlineMsg:  " + response.getResponseString());
            if (!response.isOk())
                return;

            OfflineMsg offlineMsg = (OfflineMsg) response.getBaseData();
            if (offlineMsg == null || offlineMsg.getMsgList().size() <= 0)
                return;

            int size = offlineMsg.getMsgList().size();
            if (size > 0) {
                MsgMgr.getInstance().sendMsg(MsgType.MT_Msg_Offline, null);
            }

            // 逐条处理离线消息
            for (OfflineBean bean : offlineMsg.getMsgList()) {
                if (bean == null)
                    continue;
                dispatchOfflineMsg(bean);
            }
            refreshDBMsg();  // 更新信箱消息数据库表

            // 服务器每次最多取1000条，若超过则再次请求
            if (offlineMsg.getMsgList().size() >= 1000) {
                getOfflineMsg();
            }
        });
    }

    /**
     * 离线消息派发
     */
    private void dispatchOfflineMsg(OfflineBean bean) {
        BaseMessage baseMessage = bean.getBaseMessage();
        if (baseMessage.getMsgType() <= 0 ||        // 无效消息
                baseMessage.getUidTo() != ModuleMgr.getCenterMgr().getMyInfo().getUid() || // 不是自己消息
                !MsgUtils.isSaveMsg(baseMessage.getMsgType()))   // 无需存储消息
            return;

        initMailMsg(baseMessage);
        MsgUtils.handleSbUnread(baseMessage.getLuidFrom());
        ModuleMgr.getDbMgr().getMsgCache().insertMsg(baseMessage, null);
    }

    private List<Long> idList = Collections.synchronizedList(new ArrayList<>());  // 未读用户id集合
    private Map<Long, BaseMessage> lastMsgMap = new HashMap<>();  // 未读用户id集合

    private void initMailMsg(BaseMessage baseMessage) {
        long uidFrom = baseMessage.getLuidFrom();
        if (!idList.contains(uidFrom)) {
            idList.add(uidFrom);
            lastMsgMap.put(uidFrom, baseMessage);
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            lastMsgMap.replace(uidFrom, baseMessage);
            return;
        }
        lastMsgMap.remove(uidFrom);
        lastMsgMap.put(uidFrom, baseMessage);
    }

    private void refreshDBMsg() {
        for (Long uidFrom : idList) {
            IMChatUtil.getInstance().updateMsgList(lastMsgMap.get(uidFrom));
        }
    }

    // ========================================== Http ======================

    /**
     * 获取离线消息: 客户端每次最多只处理1000条离线消息
     */
    private void reqOfflineMsg(RequestComplete complete) {
        Map<String, Object> getParams = new HashMap<>();
        getParams.put("limit", 1000);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqOfflineMsg, getParams, complete);
    }
}
